package com.googlecode.bizyap.core;

import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import com.googlecode.bizyap.core.logging.Logger;
import com.googlecode.bizyap.core.logging.LoggerFactory;


public class AgentService {

	private static final Logger log = LoggerFactory.getLogger(AgentService.class);
	private static final long _1_MINUTE = 1000L * 60 * 1;
	private static final AgentService INSTANCE = new AgentService();

	public static AgentService get(){
		return INSTANCE;
	}

	private final Timer timer = new Timer(true);
	private final Configuration conf ;
	private volatile Map<String, Application> applications = new ConcurrentHashMap<String, Application>();
	private volatile boolean valid = true;

	private AgentService(){
		super();
		log.info("creating AgentService...");

		// searches CONFIGURATION_FILE in 3 locations respectively:
		// 1. catalina.home/conf directory (e.g. ../tomcat/conf/CONFIGURATION_FILE)
		// 2. user.dir directory (e.g. ../tomcat/bin/CONFIGURATION_FILE)
		// 3. in classpath : CONFIGURATION_PKG/CONFIGURATION_FILE

		conf = new Configuration(Globals.CONFIGURATION_FILE);
		createApplications();
		initTimer();
	}

	private void initTimer() {
		TimerTask task = new TimerTask(){
			@Override
			public void run() {
				createApplications();
			}
		};

		timer.scheduleAtFixedRate(task, _1_MINUTE, _1_MINUTE);
	}

	private void createApplications(){
		try {
			if(conf.readConfiguration()) {
				Set<Application> apps = conf.getApplications();
				Map<String, Application> temp = new ConcurrentHashMap<String, Application>();
				for (Application app : apps) {
					log.info("SECURE APP: " + app.getContextPath());
					temp.put(app.getContextPath(), app);
				}
				applications = temp;
				valid = true;
			}
		} catch (Exception e) {
			valid = false;
			log.error("while reading configuration file!", e);
		}
	}

	public String getSsoLoginUrl(){
		return conf.getSSOLoginUrl();
	}

	public String getSsoLogoutUrl(){
		return conf.getSSOLogoutUrl();
	}

	public String getSsoAuthUrl(){
		return conf.getSSOAuthUrl();
	}
	
	public String getLoggerType() {
		return conf.getLoggerType();
	}

	public Application getApplication(String path) {
		if(!valid){
			log.error("AgentService is not valid.. Please check SSO configuration file!");
			return new Application(path, false);
		}

		Application app = applications.get(path);
		if(app==null) {
			synchronized (this) {
				if(app==null){
					app = new Application(path);
					applications.put(path, app);
				}
			}
		}
		return app;
	}
	
	public static void main(String[] args) {
		System.err.println(AgentService.get().getLoggerType());
	}

}
